﻿#region 命名空间

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Ext.Net;
using Sharp.DataTransferObject;
using Sharp.Infrastructure;
using Sharp.Infrastructure.WebApiClient;
using Sharp.Portal.ExtNet;
using Sharp.ServiceContracts;
using Sharp.WebBooter.Areas.Platform.Models;
using PartialViewResult = Ext.Net.MVC.PartialViewResult;

#endregion

namespace Sharp.WebBooter.Areas.Platform.Controllers
{
    [Authorize]
    public class PermissionController : Controller
    {
        // GET: Manage/Permission
        public ActionResult ListForUser(string userName)
        {
            List<PermissionDTO> userPermissions;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                userPermissions = proxy.Channel.GetPermissionByUserName(userName).ToList();
            }

            var pv = new PartialViewResult
            {
                ViewName = "TreeList",
                Model = Data(userPermissions)
            };

            return pv;
        }

        public ActionResult ListForRole(int? ownerId)
        {
            IEnumerable<PermissionDTO> permissions;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                permissions = proxy.Channel.GetPermissionByRoleId(ownerId.Value).Result;
            }

            return new PartialViewResult
            {
                ViewName = "TreeList",
                Model = Data(permissions)
            };
        }

        public ActionResult Save(string owner, int? ownerId)
        {
            Guid[] ids = HttpContext.Request["ids"].FromJson<Guid[]>();

            if (ownerId == null)
            {
                throw new ArgumentNullException(nameof(ownerId));
            }
            Result res;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                res = proxy.Channel.SavePermission(ids, owner, ownerId.Value);
            }

            return this.JsonNet(res);
        }

        private PermissionTreeListViewModel Data(IEnumerable<PermissionDTO> userPermissions)
        {
            var builder = new TreeBuilder<Guid, PermissionDTO>
            {
                ChangeData = (p, treeNode) =>
                {
                    treeNode.Text = p.Title;
                    treeNode.NodeID = p.Id.ToString();
                    treeNode.Checked = userPermissions.Any(x => x.Id == p.Id);
                    if (new[] { "02", "04", "08" }.Any(c => c == p.Category))
                        treeNode.Expanded = false;
                    else
                        treeNode.Expanded = true;
                    treeNode.AutoDataBind = false;
                }
            };

            var vm = new PermissionTreeListViewModel();
            IList<PermissionDTO> list;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                list = proxy.Channel.AllPermissions().Result.ToList();
            }

            var systemlist = list
                .GroupBy(x => x.SystemCode)
                .ToDictionary(x => x.Key, g => g.OrderBy(x => x.OrderIndex).ToList());

            IList<SubSystemDTO> subSystems;
            using (var proxy = new WebApiClientServiceProxy<IPlatformService>())
            {
                subSystems = proxy.Channel.GetSubSystems();
            }

            foreach (var system in subSystems)
            {
                vm.LeftTrees.Add(system.Code, new Node()
                {
                    Text = ".",
                    NodeID = system.Code + "Root",
                    Expanded = true,
                    AutoDataBind = false,
                    Checked = null
                });

                builder.Build(systemlist[system.Code], vm.LeftTrees.Last().Value, null);

                vm.Systems.Add(system);
            }

            return vm;
        }

    }
}